package com.example.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pt.dto.TorrentSeedInfoDTO;
import com.example.pt.entity.TorrentSeedStats;
import com.example.pt.mapper.TorrentSeedStatsMapper;
import com.example.pt.service.TorrentSeedStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class TorrentSeedStatsServiceImpl extends ServiceImpl<TorrentSeedStatsMapper, TorrentSeedStats> implements TorrentSeedStatsService {
    
    private static final Logger logger = LoggerFactory.getLogger(TorrentSeedStatsServiceImpl.class);
    
    @Override
    @Transactional
    public boolean updateSeedStats(String infoHash, Integer seeders, Integer leechers, Integer completed) {
        if (infoHash == null || infoHash.isEmpty()) {
            logger.error("更新做种统计失败：InfoHash为空");
            return false;
        }
        
        // 查询是否已存在记录
        TorrentSeedStats existingStats = getStatsByInfoHash(infoHash);
        
        if (existingStats != null) {
            // 更新现有记录
            logger.debug("更新种子做种统计：infoHash={}, 做种={}, 下载中={}, 完成={}",
                    infoHash, seeders, leechers, completed);
            
            existingStats.setSeeders(seeders);
            existingStats.setLeechers(leechers);
            existingStats.setCompleted(completed);
            existingStats.setLastUpdated(new Date());
            
            return updateById(existingStats);
        } else {
            // 创建新记录
            logger.info("创建种子做种统计：infoHash={}, 做种={}, 下载中={}, 完成={}",
                    infoHash, seeders, leechers, completed);
            
            TorrentSeedStats stats = new TorrentSeedStats();
            stats.setInfoHash(infoHash);
            stats.setSeeders(seeders);
            stats.setLeechers(leechers);
            stats.setCompleted(completed);
            stats.setLastUpdated(new Date());
            
            return save(stats);
        }
    }
    
    @Override
    public TorrentSeedStats getStatsByInfoHash(String infoHash) {
        if (infoHash == null || infoHash.isEmpty()) {
            return null;
        }
        
        LambdaQueryWrapper<TorrentSeedStats> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TorrentSeedStats::getInfoHash, infoHash);
        
        return getOne(queryWrapper);
    }
    
    @Override
    public TorrentSeedInfoDTO getTorrentSeedInfoByTid(Integer tid) {
        if (tid == null) {
            logger.error("查询种子做种信息失败：种子ID为空");
            return null;
        }
        
        logger.debug("查询种子做种信息：tid={}", tid);
        return baseMapper.findTorrentSeedInfoByTid(tid);
    }
} 